import os
import sys

# 设置fastdfs的版本
LIBFAST_VERSION = '1.0.7'
FAST_VERSION = '5.05'

class FASTManager(object):

    def __init__(self,libversion='1.0.7',fastversion='5.05'):
        self.libversion = libversion
        self.fastversion = fastversion

    def install_libfastcommon(self):
        """
        安装libfastcommon
        :return:
        """
        try:
            print('开始下载libfastcommon。。。')
            os.system('cd /soft/ && wget https://github.com/happyfish100/libfastcommon/archive/V%s.tar.gz' % self.libversion)
            # 解压
            print("解压。。。")
            print("\n-------\n")
            os.system('tar -zxvf /soft/V%s.tar.gz -C /soft/' % self.libversion)
            # 删除下载包
            os.remove('/soft/V%s.tar.gz' % self.libversion)

            # 编译安装
            print("编译测试安装。。。。。。")
            os.system('cd /soft/libfastcommon-%s && ./make.sh && ./make.sh install' % self.libversion)

            # 创建软链接
            os.system('ln -s /usr/lib64/libfastcommon.so /usr/local/lib/libfastcommon.so')
            os.system('ln -s /usr/lib64/libfastcommon.so /usr/lib/libfastcommon.so')
            os.system('ln -s /usr/lib64/libfdfsclient.so /usr/local/lib/libfdfsclient.so')
            os.system('ln -s /usr/lib64/libfdfsclient.so /usr/lib/libfdfsclient.so')

            return True
        except Exception as e:
            print(e)
            return False

    def install_fastdfs(self):
        """
        安装FastDFS
        :return:
        """
        try:
            # 切换目录下载FastDFS
            print("开始下载FastDFS")
            os.system('cd /soft/ && wget https://github.com/happyfish100/fastdfs/archive/V%s.tar.gz'%FAST_VERSION)
            # 解压
            print("解压。。。")
            print("\n-------\n")
            os.system('tar -zxvf /soft/V%s.tar.gz -C /soft/'%FAST_VERSION)
            # 删除下载包
            os.remove('/soft/V%s.tar.gz'%FAST_VERSION)
            # 编译安装
            print("编译测试安装。。。。。。")
            os.system('cd /soft/fastdfs-5.05 && ./make.sh && ./make.sh install')
            print("安装完毕!")
            print("\n-------\n")
            print('创建软链接。。。')
            os.system('ln -s /usr/bin/fdfs_trackerd   /usr/local/bin/')
            os.system('ln -s /usr/bin/fdfs_storaged   /usr/local/bin/')
            os.system('ln -s /usr/bin/stop.sh         /usr/local/bin/')
            os.system('ln -s /usr/bin/restart.sh      /usr/local/bin/')

        except Exception as e:
            print(e)
        else:
            print("安装完毕！请测试！")

if __name__ == '__main__':
    if len(sys.argv) == 1:
        print("默认安装fastdfs5.05。。。")
        fast = FASTManager()
        if fast.install_libfastcommon():
            fast.install_fastdfs()
    elif len(sys.argv) == 3:
        fast = FASTManager(libversion=sys.argv[1],fastversion=sys.argv[2])
        if fast.install_libfastcommon():
            fast.install_fastdfs()
    else:
        print("参数错误！")